<template>
  <div class="departments-container">
    <el-card>
      <tree-tools :tree-node="company" :is-root="false" @add="handlerAdd" />
    </el-card>
    <el-card>
      <el-tree v-loading="loading" :data="departs" :props="defaultProps" default-expand-all>
        <tree-tools slot-scope="{data}" :tree-node="data" @add="handlerAdd" @edit="handlerEdit" @refresh="getDepartments" />
      </el-tree>
    </el-card>
    <add-dept ref="addDept" :dialog-visible.sync="dialogVisible" :current-node="currentNode" />
  </div>
</template>

<script>
import { getDepartmentsApi } from '@/api/departments'
import { tranListToTreeData } from '@/utils'
import TreeTools from './components/TreeTools.vue'
import AddDept from './components/add-dept.vue'
export default {
  name: 'DepartmentsIndex',
  components: { TreeTools, AddDept },
  data() {
    return {
      departs: [],
      defaultProps: {
        label: 'name' // 修改树形结构默认显示的标签名
      },
      company: { name: '江苏传智播客教育科技股份有限公司', manager: '负责人', id: '' },
      dialogVisible: false, // 控制弹框显隐
      currentNode: {}, // 当前点击节点信息
      loading: false
    }
  },
  created() {
    this.getDepartments()
  },
  methods: {
    async getDepartments() {
      try {
        this.loading = true
        const res = await getDepartmentsApi()
        this.departs = tranListToTreeData(res.depts, '')
        // console.log(res)
        this.company = { name: res.companyName, manager: res.companyManager, id: '' }
      } finally {
        this.loading = false
      }
    },
    handlerAdd(node) {
      this.dialogVisible = true
      this.currentNode = node // 当前点击的那个节点信息
    },
    handlerEdit(node) {
      // 展示弹框
      this.dialogVisible = true
      // 传入信息
      this.$refs.addDept.formData = { ...node }
      // 保存当前节点信息，不管用不用，得保证数据的干净
      this.currentNode = node // 当前点击的那个节点信息
    }
  }
}
</script>

<style lang="scss" scoped>
.departments-container {
  width: 900px;
  margin: 20px auto;
  .el-tree::v-deep  {
    .el-tree-node__content {
      padding-right: 20px;
    }
  }
}
</style>

